<template>
	<view>
		<cu-custom bgColor="bg-white" :isBack="true">
			<block slot="content">{{ form.id ? '编辑' : '新增' }}地址</block>
		</cu-custom>
		<view id="container" class="map-container" :style="style" v-if="showMap"></view>
		<view class="form">
			<view class="box padding-lg">
				<view class="item crow margin-bottom-xl" @tap="openRegions">
					<view class="left text-left">选择地址</view>
					<view class="right">
						<view class="uni-input-wrapper">
							<text v-if="form.province_id">{{ form.province }} {{ form.city }} {{ form.area }}
								{{ form.street }}</text>
							<text class="uni-input-placeholder input-placeholder" v-else>请选择地址</text>
						</view>
					</view>
					<view class="cuIcon-right locationfill"></view>
				</view>
				<view class="item crow margin-bottom-xl">
					<view class="left text-left">详细地址</view>
					<textarea class="right" v-model="form.address_detail" auto-height maxlength="200"
						placeholder="详细地址，例如：XX小区X栋X单元X楼8888号"></textarea>
				</view>
				<view class="item crow margin-bottom-xl">
					<view class="left text-left">联系人</view>
					<view class="right">
						<input type="text" placeholder="请输入联系人" v-model="form.name">
					</view>
				</view>
				<view class="item crow margin-bottom-xl">
					<view class="left text-left">联系电话</view>
					<view class="right">
						<input type="tel" placeholder="请输入联系电话" v-model="form.mobile" maxlength="11">
					</view>
				</view>
				<view class="item crow">
					<view class="left text-left">设为默认</view>
					<view class="right"></view>
					<u-switch v-model="form.is_default" :activeValue="1" :inactiveValue="0" activeColor="var(--theme-color)"
						style="transform: scale(0.7);">
					</u-switch>
				</view>
			</view>

			<view class="padding margin-top-lg">
				<view class="flex flex-direction">
					<button class="cu-btn china-btn-bg lg round" @click="submit()">保存</button>
				</view>
			</view>
		</view>
		<x-regions ref="xRegionsRef" @selected="selectedRegions" />
		<loading v-if="pageLoading" />

	</view>
</template>

<script>
let map,mapContainer,mapMarker;
export default {
	data() {
		return {
			pageLoading: false,
			showMap:false,
			form: {
				id: '',
				province_id: '',
				province: '',
				city_id: '',
				city: '',
				area_id: '',
				area: '',
				street_id: '',
				street: '',
				address_detail: '',
				name: '',
				mobile: '',
				is_default: 0,
				latitude: '',
				longitude: '',
			},

		};
	},
	computed: {
		style() {
			let style = '';
			if (!this.$utils.$system.isWechat()) {
				style = `height:calc(50vh - ${this.StatusBar}px - ${this.CustomBar}px);`
			}
			return style
		}
	},
	onLoad(options) {
		if (options.id) {
			this.pageLoading = true;
			this.$utils.$api.Address.getAddressDetails(options.id).then(data => {
				this.form = data;
				this.initAMap();
			}).finally(() => {
				this.pageLoading = false;
			});
		} else {
			this.initAMap();
		}
	},
	unLoad(){
		mapContainer&&mapContainer.destroy();
	},
	methods: {
		submit() {
			uni.showLoading({ title: '保存中...' });
			this.$utils.$api.Address.saveAddress(this.form).then(res => {
				uni.hideLoading();
				this.$utils.$message.success(res.msg);
				setTimeout(() => {
					this.$utils.$page.back();
				}, 1000);
			}).catch(err => {
				uni.hideLoading();
				this.$utils.$message.error(err.msg);
			})
		},
		openRegions() {
			this.$refs.xRegionsRef.show();
		},
		selectedRegions(regions) {
			this.form = Object.assign(this.form, regions);
			if (!regions.street_id) {
				this.form.street_id = '';
				this.form.street = '';
			}
		},
		initAMap() {
			map = this.$utils.useMap(()=>{
				this.showMap=true;
				this.$nextTick(()=>{
					map.createMap("container").then(res=>{
						mapContainer=res;
						let lnglat;
						if(this.form.longitude, this.form.latitude){
							lnglat=[this.form.longitude, this.form.latitude];
						}
						map.createMarker(mapContainer,lnglat).then(res=>{
							mapMarker=res;
							mapContainer.on('click', (e) => {
								mapMarker.moveTo([e.lnglat.lng, e.lnglat.lat]);
								mapContainer.setCenter([e.lnglat.lng, e.lnglat.lat]);
							});
							mapContainer.on('touchend', () => {
								const center=mapContainer.getCenter();
								mapMarker.moveTo([center.lng, center.lat]);
							});
							mapContainer.on('moveend', () => {
								if(this.pageLoading){return;}
								this.pageLoading=true;
								const center=mapContainer.getCenter();
								this.form.latitude=center.lat;
								this.form.longitude=center.lng;
								map.getAddress([center.lng, center.lat]).then(result=>{
									const formattedAddress=result.regeocode.formattedAddress;
									const addressComponent=result.regeocode.addressComponent;
									this.form.address_detail=formattedAddress
									.replace(addressComponent.province+addressComponent.city+addressComponent.district+addressComponent.township,'');
									this.$refs.xRegionsRef.search({
										province:addressComponent.province,
										city:addressComponent.city,
										area:addressComponent.district,
										street:addressComponent.township
									});
									this.pageLoading=false;
								}).catch(err=>{
									this.pageLoading=false;
									console.log(err);
								})
							});
						});
					}).catch(err=>{
						console.log(err);
					});
					if(!this.form.id){
						map.getCurrentPosition().then((result) => {
							mapContainer&&mapContainer.setCenter([result.position.lng, result.position.lat]);
							mapMarker&&mapMarker.moveTo([result.position.lng, result.position.lat]);
						}).catch((err) => {
							console.log(err);
						});
					}
				})
			});
		},
	}
}
</script>

<style lang="less" scoped>
page{
	background-color: #FFFFFF;
}
.form {
	min-height: 50vh;
}

.box {
	.item {
		width: 100%;

		.left {
			width: 25%;
		}

		.right {
			width: 69%;

			input {
				font-size: 26upx;
			}
		}

		.locationfill {
			font-size: 35upx;
		}
	}
}

.map-container {
	padding: 0px;
	margin: 0px;
	width: 100%;
	height: 50vh;
}
</style>
